<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\QuestionCate;
use app\common\model\QuestionGroup;
use app\common\model\Exampaper;
use app\common\model\Question as ModelQuestion;
use app\common\model\QuestionPaper;
use app\common\model\UserAnswers;
use app\common\model\UserQuestion;
use app\common\model\UserQuestionReport;
use think\Db;
use think\exception\DbException;
use think\exception\HttpResponseException;
use think\Loader;
use think\Request;

/**
 * 刷题管理
 * @package app\api\controller
 */
class Question extends Api
{
    protected $noNeedLogin = [''];

    protected $noNeedRight = ['*'];

    /**
     * 根据分类ID查询所有刷题列表
     * @return void
     */
    public function list()
    {
        $type = $this->request->param('type', '1'); # 1=全部,2=传二级分类id
        if (!in_array($type, [1, 2])) {
            $this->error("参数错误");
        }
        $cate_id = $this->request->param('cate_id', 0); //分类id 根据type判断定传入几级id
        $list = (new QuestionGroup())->getList(['cate_id' => $cate_id], $type, $this->auth->id);
        $this->success('', $list);
    }

    /**
     * 有三级分类刷题列表详情（根据三级分类查询）
     */
    public function details()
    {
        $cate_id = $this->request->param('cate_id', 0); # 三级分类ID
        if (!$cate_id) {
            $this->error('分类ID不能为空');
        }
        $row = (new QuestionGroup())->getDetails($cate_id, $this->auth->id);
        $this->success('', $row);
    }

    /**
     * 添加到首页刷题
     * @return void 
     */
    public function userQuestionAdd()
    {
        $user_id =  $this->auth->id;
        $question_group_id = $this->request->param('question_group_id', 0);
        $row = (new UserQuestion())->saveUserQuestionAdd($user_id, $question_group_id);
        if ($row) {
            $this->success('添加成功', $row);
        } else {
            $this->error('添加失败');
        }
    }

    /**
     * 移除刷题
     * @return void 
     */
    public function userQuestionRemove()
    {
        $user_id = $this->auth->id;
        $question_group_id = $this->request->param('question_group_id', 0);
        $row = (new UserQuestion())->removeUserQuestion($user_id, $question_group_id);
        if ($row) {
            $this->success('移除成功', $row);
        } else {
            $this->error('移除失败');
        }
    }


    /**
     * 题库信息列表
     * @return void 
     */
    public function questionList()
    {
        $question_group_id = $this->request->param('question_group_id', 0);
        if (!$question_group_id) {
            $this->error('刷题组ID不能为空');
        }
        $row = (new QuestionPaper())->getQuestionPaperList($question_group_id, $this->auth->id);
        if (!$row) {
            $this->error('暂无数据');
        }
        $this->success('', $row);
    }

    /**
     * 用户答题
     * @param Request $request 
     * @param UserAnswers $userAnswers 
     * @return void 
     */
    public function userAnswers(Request $request, UserAnswers $userAnswers)
    {
        $param = $request->param();
        $param['user_id'] = $this->auth->id;
        # 验证
        $validate = Loader::validate('Question');
        if (!$validate->scene('user_answers')->check($param)) {
            $this->error($validate->getError());
        }
        $row = $userAnswers->saveUserAnswers($param);
        if (!$row) {
            $this->error($userAnswers->getError());
        }
        $this->success("保存成功");
    }



    /**
     * 提交刷题报告
     */
    public function submitQuestion(Request $request)
    {
        $user_id = $this->auth->id;
        $param = $request->param();
        if (empty($param)) {
            $this->error("参数错误");
        }
        # 刷题组卷信息
        $infoQuestionGroup = Db::name('question_group')->where('id', $param['question_group_id'])->find();
        if (empty($infoQuestionGroup)) {
            $this->error("刷题组卷信息不存在");
        }
        # 查询用户答题
        $list = Db::name('user_answers')->where('user_id', $user_id)->where('question_group_id', $param['question_group_id'])->select();
        if (empty($list)) {
            $this->error("暂无答题信息");
        }
        $userAnswersCount = count($list);
        $rightCount = 0;
        $wrongCount = 0;
        $blankCount = 0;
        foreach ($list as $value) {
            if ($value['is_right'] == 1) {
                $rightCount++;
            }
            if ($value['is_right'] == 0) {
                $wrongCount++;
            }
            # 单选题 简答题 未答
            if ($value['is_right'] == -1 || ($value['is_right'] == 3 && $value['answer'] == '')) {
                $blankCount++;
            }
        }
        # 计算刷题总数
        $param['right_count'] = $rightCount;
        $param['wrong_count'] = $wrongCount;
        $param['blank_count'] = $blankCount;
        $user_question_report = (new UserQuestionReport())->saveUserQuestionReport($user_id, $param);
        $this->success("提交成功", [
            'user_question_report' => $user_question_report,
            'question_group_name' => $infoQuestionGroup['name'],
        ]);
    }

    
    public function getQuestionSelect(Request $request){
        $user_id = $this->auth->id;
        $param = $request->param();
        if (empty($param)) {
            $this->error("参数错误");
        }
         # 刷题组卷信息
        $infoQuestionGroup = Db::name('question_group')->where('id', $param['question_group_id'])->find();
        if (empty($infoQuestionGroup)) {
            $this->error("刷题组卷信息不存在");
        }
        $user_question_report = Db::name('user_question_report')->where('user_id', $user_id)->where('question_group_id', $param['question_group_id'])->find();
        $this->success("获取成功", [
            'user_question_report' => $user_question_report,
        ]);
    }

    /**
     *  圆环图统计
     */
    public function donutChartStatistics(){
        $user_id = $this->auth->id;
        $question_group_id = input('question_group_id', 0);
        
        if (!$question_group_id) {
            $this->error('刷题组卷ID不能为空');
        }
        
        // 查询该用户在指定刷题组卷下的错题统计，按模块分组
        $errorStats = Db::name('user_answers')
            ->alias('ua')
            ->join('mock m', 'ua.mock_id = m.id')
            ->where('ua.user_id', $user_id)
            ->where('ua.question_group_id', $question_group_id)
            ->where('ua.in_error', 1) // 只统计错题
            ->field('ua.mock_id, m.name as mock_name, COUNT(*) as error_count')
            ->group('ua.mock_id')
            ->select();
        // 格式化返回数据
        $result = [];
        foreach ($errorStats as $item) {
            $result[] = [
                // 'mock_id' => $item['mock_id'],
                'name' => $item['mock_name'] ?: '未知模块',
                'value' => (int)$item['error_count']
            ];
        }
        $this->success('圆环图统计数据', $result);
    }


    /**
     * 智能推荐 - 根据用户错题考点推荐题目
     */
    public function questionRandom()
    {
        $user_id = $this->auth->id;
        $mock_id = $this->request->param('mock_id', 0);
        
        # 查询模块信息
        $infoMock = Db::name('mock')->where('id', $mock_id)->find();
        if (empty($infoMock)) {
            $this->error("模块信息不存在");
        }
        
        # 查询用户做过的错题
        $userAnswers = Db::name('user_answers')
            ->where('user_id', $user_id)
            ->where('mock_id', $mock_id)
            ->where('is_right', 0)
            ->select();
        
        $userAnswersIds = array_column((array)$userAnswers, 'question_id');
        # 如果没有错题，提示错误
        if (empty($userAnswersIds)) {
            $this->error('暂无错题记录');
            return;
        }
        
        # 查询错题对应的考点
        $errorQuestions = Db::name('question')
            ->whereIn('id', $userAnswersIds)
            ->where('deletetime', 'NULL')
            ->field('id, examination_point_ids')
            ->select();
        
        # 统计每个考点的错题数量
        $examinationPointStats = [];
        foreach ($errorQuestions as $question) {
            if (empty($question['examination_point_ids'])) {
                continue;
            }
            # 考点ID可能是逗号分隔的多个ID
            $pointIds = explode(',', $question['examination_point_ids']);
            foreach ($pointIds as $pointId) {
                $pointId = trim($pointId);
                if (!$pointId) {
                    continue;
                }
                if (!isset($examinationPointStats[$pointId])) {
                    $examinationPointStats[$pointId] = 0;
                }
                $examinationPointStats[$pointId]++;
            }
        }
       
        # 如果没有考点统计，提示错误
        if (empty($examinationPointStats)) {
            $this->error('错题无考点信息');
            return;
        }

        # 按错题数量降序排序，找出错题最多的考点
        arsort($examinationPointStats);
     
        # 取前2个错题最多的考点（可以根据需要调整数量）
        $topExaminationPoints = array_slice(array_keys($examinationPointStats), 0, 2, true);
        
        # 获取这些考点的详细信息（名称、每次随机题数）
        $examinationPointInfo = Db::name('examination_point')
            ->whereIn('id', $topExaminationPoints)
            ->field('id, name, question_count')
            ->select();
        # 转换为以ID为键的数组
        $examinationPointMap = [];
        foreach ($examinationPointInfo as $point) {
            $examinationPointMap[$point['id']] = $point;
        }
        
        # 计算总的随机题目数量（各考点的question_count之和）
        $totalQuestionCount = 0;
        $recommendInfo = [];
        foreach ($topExaminationPoints as $pointId) {
            $pointData = $examinationPointMap[$pointId] ?? null;
            if ($pointData) {
                $pointQuestionCount = (int)($pointData['question_count'] ?? 0);
                $totalQuestionCount += $pointQuestionCount;
                
                $recommendInfo[] = [
                    'point_id' => $pointId,
                    'point_name' => $pointData['name'] ?? '未知考点',
                    'error_count' => $examinationPointStats[$pointId],
                    'recommend_count' => $pointQuestionCount
                ];
            }
        }
        # 如果总题目数为0，提示错误
        if ($totalQuestionCount <= 0) {
            $this->error('考点未配置随机题目数量');
            return;
        }
        
        # 根据考点筛选题目
        # 使用总的随机题目数量（各考点question_count之和）
        $questions = Db::name('question')
            ->where('mock_id', $mock_id)
            ->where('deletetime', 'NULL')
            ->where('status', 'NORMAL')
            ->where(function($query) use ($topExaminationPoints) {
                foreach ($topExaminationPoints as $pointId) {
                    $query->whereOr('examination_point_ids', 'like', "%{$pointId}%");
                }
            })
            ->field('id as question_id,kind,title,explain,difficulty,options_json,options_img,answer,status,examination_point_ids')
            ->orderRaw('RAND()')
            ->limit($totalQuestionCount)
            ->select();
        
        # 只返回对应考点的题目，不补充其他题目
        $questions = collection($questions)->toArray();
        
        # 格式化题目数据
        $formattedQuestions = getQuestionArray($questions);
        
        $this->success('智能推荐成功', [
            'recommend_info' => $recommendInfo,
            'expected_total' => $totalQuestionCount,  // 期望的题目总数（各考点配置之和）
            'actual_total' => count($formattedQuestions),  // 实际返回的题目数
            'data' => $formattedQuestions
        ]);
    }


    /**
     * 题库信息
     * @param Request $request 
     * @return void 
     * @throws HttpResponseException 
     */
    public function cardQuestion(Request $request)
    {
        $user_id = $this->auth->id;
        $question_group_id = $request->param('question_group_id');
        $list = (new ModelQuestion())->getCardQuestion($user_id, $question_group_id);
        $this->success('success', $list);
    }

    
    /**
     * 模块列表
     * @return void 
     */
    public function mocklist(){
        $list = Db::name('mock')->where('status', '1')->where('deletetime', 'NULL')->select();
        $this->success('success', $list);
    }

    


   
}
